package net.mingsoft.report_data.schedule;

import lombok.extern.slf4j.Slf4j;
import net.mingsoft.report_data.biz.ZkDataBiz;
import net.mingsoft.report_data.entity.ZkDataReportConfigEntity;
import net.mingsoft.report_data.enums.ReportPeriodType;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author gengfa
 * @date 22/03/15
 */
@Slf4j
@Service
@ConditionalOnProperty(value = "report.auto-gen.enabled")
public class GenerateSchedule {

    private static final String ON = "1";

    @Resource
    ZkDataBiz dataBiz;

    /**
     * 周报
     */
    @Scheduled(cron = "0 0 0 ? * MON")
    void generateWeekly() {
        generate(ReportPeriodType.LAST_WEEK, 0);
    }

    /**
     * 月报
     */
    @Scheduled(cron = "0 0 0 1 * ?")
    void generateMonthly() {
        generate(ReportPeriodType.LAST_MONTH, 1);
    }

    /**
     * 季报
     */
    @Scheduled(cron = "0 0 0 1 1,4,7,10 *")
    void generateSeason() {
        generate(ReportPeriodType.LAST_SEASON, 2);
    }

    /**
     * 半年报
     */
    @Scheduled(cron = "0 0 0 1 1,7 *")
    void generateHalfYear() {
        generate(ReportPeriodType.LATTER_HALF_LAST_YEAR, 3);
    }

    /**
     * 年报
     */
    @Scheduled(cron = "0 0 0 1 1 *")
    void generateAnnual() {
        generate(ReportPeriodType.LAST_YEAR, 4);
    }

    void generate(ReportPeriodType periodType, int pos) {
        log.info("[AUTOGEN] start...");
        // 获取所有需要自动生成的报告
        List<ZkDataReportConfigEntity> reports = dataBiz.getReports();
        // 检查周期配置
        List<ZkDataReportConfigEntity> filterList =
                reports.stream().filter(
                        o -> o.getGeneratePeriod().startsWith(ON, pos)).collect(Collectors.toList());
        // 开始生成报告
        if (filterList.size() > 0) {
            log.info("[AUTOGEN] {} reports ready", filterList.size());
            dataBiz.autoGenerateReports(periodType, filterList);
        } else {
            log.info("[AUTOGEN] no reports ready");
        }
        log.info("[AUTOGEN] finished");
    }
}
